package com.ncdnapp.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * md5编码工具类
 *
 * @Author: chenbin
 * @Date: 2018-05-03
 * @Time: 16:54
 * @Description:
 */
public class Md5Util {
    /**
     * 编码
     *
     * @param value
     * @return
     */
    public static String encode(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(value.getBytes(StandardCharsets.UTF_8));
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

}
